package us.ohec.validators
{
  import us.ohec.utils.NumberUtil;
  
  import mx.validators.ValidationResult;
  import mx.validators.Validator;

	public class TFNValidator extends Validator
	{
		override protected function doValidation(value:Object): Array {
      var results:Array = super.doValidation(value);

      var val:String = value ? String(value) : "";

      if (results.length > 0 || ((val.length == 0) && ! required)) {
        return results;
      } else {
        return TFNValidator.validateTFN(val);
      }
    }

    public static function validateTFN(value:String): Array {
      var results:Array = [];

      value = NumberUtil.trim(value).toString();

      if (value.length != 9) {
        results.push(new ValidationResult(true, null, "invalidLength", "Invalid TFN length."));
        return results;
      }

      var weights:Array = [1, 4, 3, 7, 5, 8, 6, 9, 10];

    //  value = Number(value.charAt(0)) - 1 + value.substr(1);

      var sum:Number = 0;

      for (var i:int = 0; i < value.length; i++) {
        sum += Number(value.charAt(i)) * weights[i];
      }

      if (sum % 11 != 0) {
        results.push(new ValidationResult(true, null, "invalidLength", "Invalid TFN."));
      }

      return results;
    }
	}
}